<template>
	<div class="table-container">
		<div class="tableHeader">
			<el-tooltip
				class="box-item"
				effect="light"
				content="刷新"
				placement="top" >
				<el-button color="#333" @click="onRefreshTable"><i class="fa fa-refresh"></i></el-button>
			</el-tooltip>
			<div class="btnItem" v-if="getConfig.isExcel&&getConfig.isSelection">
				<el-tooltip
					effect="light"
					content="导出"
					placement="top" >
					<el-button @click="onImportTable" :disabled="state.selectlist.length>0?false:true"><i class="fa fa-cloud-download"></i></el-button>
				</el-tooltip>
			</div>
			<div class="btnItem" v-if="btn.indexOf('del')>0&&getConfig.isSelection" >
				<el-tooltip
					effect="light"
					content="删除选中的行"
					placement="top" >
					<el-button type="danger" @click="delAllBtn" :disabled="state.selectlist.length>0?false:true"><i class="fa fa-trash"></i>删除</el-button>
				</el-tooltip>
			</div>
			<div class="btnItem" v-if="getConfig.isSelection" v-for="item,index in topBtn" :key="index">
				<el-tooltip
					effect="light"
					:content="item.content"
					placement="top" >
					<el-button :type="item.type" @click="zdyBtn(item.key)" :disabled="state.selectlist.length>0?false:true"><i class="fa " :class="item.icon"></i>{{item.title}}</el-button>
				</el-tooltip>
			</div>
			<div class="floatRight">
				<el-popover
					placement="bottom-end"
					trigger="click"
					transition="el-zoom-in-top"
					popper-class="table-tool-popper"
					:width="300"
					:persistent="false"
					@show="onSetTable"
				>
					<template #reference>
						<el-button color="#dcdfe6" ><i class="fa fa-th" title="设置"></i></el-button>
					</template>
					<template #default>
						<div>
							<div class="tool-box">
								<el-tooltip content="拖动进行排序" placement="top-start">
									<SvgIcon name="fa fa-question-circle-o" :size="17" class="ml11" color="#909399" />
								</el-tooltip>
								<el-checkbox
									v-model="state.checkListAll"
									:indeterminate="state.checkListIndeterminate"
									class="ml10 mr1"
									label="列显示"
									@change="onCheckAllChange"
								/>
								<el-checkbox v-model="getConfig.isSerialNo" class="ml12 mr1" label="序号" />
								<el-checkbox v-if="false" v-model="getConfig.isSelection" class="ml12 mr1" label="多选" />
								<el-checkbox v-model="getConfig.isBorder" class="ml12 mr1" label="边框" />
							</div>
							<div class="setMenu"  ref="toolSetRef">
								<div class="tool-item" v-for="v in header" :key="v.prop" :data-key="v.prop">
									<i class="fa fa-arrows-alt handle cursor-pointer"></i>
									<el-checkbox v-model="v.show" class="ml12 mr8" :label="v.label" @change="onCheckChange" />
								</div>
							</div>
						</div>
					</template>
				</el-popover>
			</div>
		</div>
		<el-table
			:data="data"
			:border="setBorder"
			v-bind="$attrs"
			row-key="id"
			stripe
			style="width: 100%"
			v-loading="config.loading"
			@selection-change="onSelectionChange"
			@sort-change="sortBtn"
		>
			<el-table-column type="selection" :reserve-selection="true" width="30" v-if="config.isSelection" />
			<el-table-column type="index" label="序号" align="center" width="60" v-if="config.isSerialNo" />
			<el-table-column
				v-for="(item, index) in setHeader"
				:key="index"
				show-overflow-tooltip
				:prop="item.prop"
				min-width="150"
				:width="item.width"
				:label="item.label"
				:align="item.align"
				:sortable="item.paixu?true:false"
			>
				<template v-slot="scope" >
					<div @click="columnClick(item,scope.row)">
						<template v-if="item.type == 'img'">
							<!-- <img :src="scope.row[item.prop]" :width="item.imgWidth" :height="item.imgHeight" /> -->
							<el-image :style="'width:'+item.imgWidth+'px; height:'+item.imgHeight+'px'" :src="scope.row[item.prop]" preview-teleported  :preview-src-list="[scope.row[item.prop]]" fit="cover" />
						</template>
						<template v-if="item.type == 'text'">
							{{ scope.row[item.prop] }}
						</template>
						<template v-if="item.type == 'data'">
							<div class="k-line-1 columnData">
								{{ scope.row[item.prop] }}
							</div>
						</template>
						<template v-if="item.type == 'tag'">
							<el-tag :type="scope.row[item.prop].type" class="mx-1" effect="dark" >
								{{ scope.row[item.prop].label }}
							</el-tag>
						</template>
						<template v-if="item.type == 'link'">
							<el-button type="primary" link>{{ scope.row[item.prop] }}</el-button>
						</template>
						<template v-if="item.type == 'user'">
							<div v-if="scope.row[item.prop].uid">
								<el-popover
									placement="top-start"
									width="aotu"
									trigger="hover"
								>
									<template #reference>
									<el-button type="primary"  link>{{ scope.row[item.prop].uname }}</el-button>
									</template>
									<template #default>
										<div>
											<el-avatar v-if="scope.row[item.prop].photo"
												:size="60"
												:src="scope.row[item.prop].photo"
												style="margin-bottom: 8px"
											/>
											<div v-if="scope.row[item.prop].uid" @click.stop="copyText(scope.row[item.prop].uid)"><el-button type="primary"  link>UID：{{scope.row[item.prop].uid}}</el-button></div>
											<div v-if="scope.row[item.prop].email" @click.stop="copyText(scope.row[item.prop].email)"><el-button type="primary"  link>邮箱：{{scope.row[item.prop].email}}</el-button></div>
											<div v-if="scope.row[item.prop].phone" @click.stop="copyText(scope.row[item.prop].phone)"><el-button type="primary"  link>手机号码：{{scope.row[item.prop].phone}}</el-button></div>
											</div>
									</template>
								</el-popover>
							</div>
							<div v-else>
								<el-button type="primary"  link>{{ scope.row[item.prop].uname }}</el-button>
							</div>
						</template>
						<template v-if="item.type == 'list'">
							<div v-for="it,idx in scope.row[item.prop]" :key="idx">
								{{idx}}：{{it}}
							</div>
						</template>
						<template v-if="item.editor">
							<div class="k-disply-inline-block">
								<el-button link type="primary"  @click="editorBtn(item,scope.row)"><i class="fa fa-pencil-square-o"></i></el-button>
							</div>
						</template>
					</div>
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作" min-width="200" align="center" v-if="getBtn.length>0">
				<template v-slot="scope">
					<div class="btnItem" v-for="(item,index) in getBtn" :key="index">
						<el-tooltip
							class="box-item"
							effect="dark"
							:content="item.title"
							placement="top" >
							<el-button circle  :type="item.type" size="default" @click="columnCzBtn(item,scope.row)"><i class="oneIcon fa" :class="item.icon"></i></el-button>
						</el-tooltip>
					</div>
				</template>
			</el-table-column>
			<template #empty>
				<el-empty description="暂无数据" />
			</template>
		</el-table>
		<div class="pagination-block clearfix">
				<div class="pagination-right">
					<el-pagination
						v-model:current-page=" state.pages.pno"
						v-model:page-size=" state.pages.pageSize"
						:total="config.total"
						:page-sizes="[10, 20, 50, 100, 200]"
						layout="total, sizes, prev, pager, next, jumper"
						@size-change="onHandleSizeChange"
						@current-change="onHandleCurrentChange"
					>
					</el-pagination>
				</div>
		</div>
		<el-dialog v-model="state.detailShow" :title="state.title">
			<div>{{state.details}}</div>
		</el-dialog>
		<el-dialog v-model="state.editorShow" :title="state.editorData.title">
			<div><el-input v-model="state.editorData.row[state.editorData.item.prop]" /></div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.editorShow = false;">取消</el-button>
					<el-button type="primary" @click="quedingBtn">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="netxTable">
import { reactive, computed, nextTick, ref } from 'vue';
import { ElMessage } from 'element-plus';
import table2excel from 'js-table2excel';
import Sortable from 'sortablejs';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import '/@/theme/tableTool.scss';
import commonFunction from '/@/utils/commonFunction';//复制
const { copyText } = commonFunction();

// 定义父组件传过来的值
const props = defineProps({
	// 列表内容
	data: {
		type: Array<EmptyObjectType>,
		default: () => [],
	},
	// 表头内容
	header: {
		type: Array<EmptyObjectType>,
		default: () => [],
	},
	// 操作按钮
	btn: {
		type: Array<EmptyObjectType>,
		default: () => [],
	},
	// 顶部自定义操作按钮
	topBtn: {
		type: Array<EmptyObjectType>,
		default: () => [],
	},
	// 搜索参数
	param: {
		type: Object,
		default: () => {},
	},
	// 配置项
	config: {
		type: Object,
		default: () => {},
	},
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['columnCzBtn', 'pageChange', 'sortHeader','columnClick']);

// 定义变量内容
const toolSetRef = ref();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const state = reactive({
	pages: {
		pno: 1,
		pageSize: 10,
	},
	selectlist: [] as EmptyObjectType[],
	checkListAll: true,
	checkListIndeterminate: false,
	detailShow:false,
	details:"",
	title:"",
	editorData:{
		row:{"paixu":""},
		item:{prop:"paixu"},
		title:"",
		originalData:"",
	},
	editorShow:false,
});

// 修改
const editorBtn=(item:object,row: EmptyObjectType[])=>{
	state.editorData.item=item;
	state.editorData.row=row;
	state.editorData.originalData=row[item.prop];
	state.editorData.title="修改"+item.label;
	state.editorShow=true;
}
// 确定修改
const quedingBtn=()=>{
	// console.log(state.editorData)
	if(state.editorData.row[state.editorData.item.prop]!=state.editorData.originalData){
		let dt={
			key:'editTable',
			data:state.editorData
		}
		emit('columnCzBtn', dt);
	}
	state.editorShow=false;
}

// 设置边框显示/隐藏
const setBorder = computed(() => {
	return props.config.isBorder ? true : false;
});
// 获取父组件 配置项（必传）
const getConfig = computed(() => {
	return props.config;
});
// 获取父组件操作按钮 （必传）
const getBtn = computed(() => {
	let btn=[];
	for(let p of props.btn){
		if(p=='editor'){
			btn.push({
				title:"修改",
				key:p,
				type:"warning",
				icon:"fa-pencil-square-o"
			})
		}
		if(p=='del'){
			btn.push({
				title:"删除",
				key:p,
				type:"danger",
				icon:"fa-trash"
			})
		}
		if(p=='role'){
			btn.push({
				title:"取消权限",
				key:p,
				type:"info",
				icon:"fa-group"
			})
		}
		if(p=='details'){
			btn.push({
				title:"详情",
				key:p,
				type:"primary",
				icon:"fa-eye"
			})
		}
	}
	return btn;
});
// 设置 tool header 数据
const setHeader = computed(() => {
	return props.header.filter((v) => v.show);
});
// tool 列显示全选改变时
const onCheckAllChange = (val: boolean) => {
	if (val) props.header.forEach((v) => (v.show = true));
	else props.header.forEach((v) => (v.show = false));
	state.checkListIndeterminate = false;
};
// tool 列显示当前项改变时
const onCheckChange = () => {
	const headers = props.header.filter((v) => v.show).length;
	state.checkListAll = headers === props.header.length;
	state.checkListIndeterminate = headers > 0 && headers < props.header.length;
};
// 表格点击
const columnClick = (item:object,row: EmptyObjectType[]) => {
	// console.log(item)
	// console.log(row)
	if(item.type=='data'){
		state.details=row[item.prop];
		state.title=item.label;
		state.detailShow=true;
	}
	let dt={
		key:item.type,
		item:item,
		data:row
	}
	emit('columnClick', dt);
};
// 表格排序点击
const sortBtn = (item:EmptyObjectType[]) => {
	// console.log(item)
	let dt={
		key:'sort',
		item:"",
		data:item
	}
	emit('columnClick', dt);
}
// 表格多选改变时，用于导出
const onSelectionChange = (val: EmptyObjectType[]) => {
	state.selectlist = val;
};
// 自定义按钮返回
const zdyBtn = (e:string) => {
	let dt={
		key:e,
		data:state.selectlist
	}
	emit('columnCzBtn', dt);
};
// 删除当前项
const delAllBtn = () => {
	let dt={
		key:'delAll',
		data:state.selectlist
	}
	emit('columnCzBtn', dt);
};
// 删除当前项
const columnCzBtn = (item:object,row: EmptyObjectType) => {
	// console.log(item)
	// console.log(row)
	let dt={
		key:item.key,
		data:row
	}
	// console.log(dt)
	emit('columnCzBtn', dt);
};
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.pages.pageSize = val;
	emit('pageChange',  state.pages);
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	 state.pages.pno = val;
	emit('pageChange',  state.pages);
};
// 搜索时，分页还原成默认
const pageReset = () => {
	 state.pages.pno = 1;
	 state.pages.pageSize = 10;
	emit('pageChange',  state.pages);
};
// 导出
const onImportTable = () => {
	if (state.selectlist.length <= 0) return ElMessage.warning('请先选择要导出的数据');
	// console.log(props.header)
	// console.log(state.selectlist)
	let header=[];
	for(let p of props.header){
		if(p.show){
			header.push(
				{
					title: p.label,
					key: p.prop,
					type: p.type=='img'?"image":'text'
				}
			)
		}
	}
	let data=[];
	for(let p of state.selectlist){
		let newp={};
		for(let t of props.header){
			if(t.type=='text'){
				newp[t.prop]=p[t.prop]
			}else if(t.type=='img'){
				newp[t.prop]=p[t.prop]
			}else if(t.type=='tag'){
				newp[t.prop]=p[t.prop].label
			}else if(t.type=='user'){
				newp[t.prop]=p[t.prop].uname
			}else{
				newp[t.prop]=p[t.prop]
			}
		}
		data.push(newp);
	}
	// console.log(header)
	// console.log(data)
	table2excel(header, data, `${props.config.excelName?props.config.excelName:themeConfig.value.globalTitle}-${new Date().toLocaleString()}`);
};
// 刷新
const onRefreshTable = () => {
	state.pages.pno = 1;
	emit('pageChange',  state.pages);
};
// 设置
const onSetTable = () => {
	nextTick(() => {
		const sortable = Sortable.create(toolSetRef.value, {
			handle: '.handle',
			dataIdAttr: 'data-key',
			animation: 150,
			onEnd: () => {
				const headerList: EmptyObjectType[] = [];
				sortable.toArray().forEach((val) => {
					props.header.forEach((v) => {
						if (v.prop === val) headerList.push({ ...v });
					});
				});
				emit('sortHeader', headerList);
			},
		});
	});
};

// 暴露变量
defineExpose({
	pageReset,
});
</script>

<style scoped lang="scss">
.table-container {
	display: flex;
	flex-direction: column;
	.el-table {
		flex: 1;
	}
	.table-footer {
		display: flex;
		.table-footer-tool {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			i {
				margin-right: 10px;
				cursor: pointer;
				color: var(--el-text-color-regular);
				&:last-of-type {
					margin-right: 0;
				}
			}
		}
	}
}
.setMenu{
	max-height: 500px;
	overflow: auto;
}
.columnData{
	cursor: pointer;
}
.btnItem{
	display: inline-block;
	margin: 0 5px;
}
.tableHeader{
	margin-bottom: 10px;
}
</style>
